package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.zhisuo.apicenter.Constants;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.ExpressManService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.StringUtil;
import com.zhisuo.apicenter.util.TcpUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 零售员相关操作
 */
@Controller
@RequestMapping(value = "/sellersman")
public class SellersManController {

    private static final Logger log = LoggerFactory.getLogger(SellersManController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    private ExpressManService expressManService;

    @Autowired
    public void setExpressManService(ExpressManService expressManService) {
        this.expressManService = expressManService;
    }

    private UserManService userManService;

    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }


    /**
     * 商家首页获取收件数量
     */
    @RequestMapping(value = "/getReceiptOrderNumBySellerUserId")
    public void getReceiptOrderNumBySellerUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderNumBySellerUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");


        Integer orderhasreciptnum=0;
        Integer orderhasorder=0;
        //待派送
        orderhasreciptnum=userManService.getHasSellerOrderNumByUserId(userid,0);
        //派送中
        orderhasorder=userManService.getHasSellerOrderNumByUserId(userid,1);
        JSONObject datajson=new JSONObject();
        datajson.put("orderhasreciptnum",orderhasreciptnum);
        datajson.put("orderhasorder",orderhasorder);
        resultObj.put("error_code",0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data",datajson);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 销售员确认选择箱子类型，触发开箱及发送短信流程
     */
    @RequestMapping(value = "/confrimSellerCarBoxTypeByCarId")
    public void confrimSellerCarBoxTypeByCarId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("confrimSellerCarBoxTypeByCarId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String carid = jsonObject.getString("carid");
        String boxcontent = jsonObject.getString("boxcontent");
        String userid = jsonObject.getString("userid");
        String receiptuserbuildid = jsonObject.getString("receiptuserbuildid");
        String receiptusermobile = jsonObject.getString("receiptusermobile");


        List<ZhiSuoCarBox> listhasZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByContent(boxcontent,carid);

        if(listhasZhiSuoCarBox==null ||listhasZhiSuoCarBox.size()==0){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "箱子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }



//        String hasreceiptuserbuildid=expressManService.getHasOrderByUserIdAndCarIdAndreceiptuserbuildid(receiptusermobile,carid);
//        if(!(StringUtil.isEmpty(hasreceiptuserbuildid)||hasreceiptuserbuildid.equals(receiptuserbuildid))){
//            resultObj.put("error_code", 1);
//            resultObj.put("error_msg", "一个用户只能选一个收件地点");
//            resultObj.put("data", "");
//            responseData(resultObj.toString(), resp);
//            return;
//        }

        String boxname=listhasZhiSuoCarBox.get(0).getName();

        ZhiSuoCarBox box = expressManService.getBoxIdByBoxName(boxname);

        if (box == null) {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "箱子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }


        ZhiSuoCar car = expressManService.getCarByCarId(Integer.parseInt(carid));
        List<ZhiSuoCarBox> listZhiSuoCarBox = expressManService.getListZhiSuoCarBoxByCarId(carid);
        DeliveryOrder order = new DeliveryOrder();
        order.setBoxcode(boxname);
        //获取TCP服务器地址
        String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");
        //下发开箱指令
        String tcpresult = TcpUtil.openDoor(car, order, listZhiSuoCarBox,tcp_url);
        if(StringUtils.isNotEmpty(tcpresult)){
            JSONObject tcpresultjson=JSONObject.parseObject(tcpresult);
            String tcpresultjsonerrorCode=tcpresultjson.getString("errorCode");
            if(tcpresultjsonerrorCode.equals("1")){
                responseErrorData("开门失败，请再试一次", resp);
                return;
            }
        }



        JSONObject oneboxjson=null;
        JSONArray opendoorarray=new JSONArray();
        for(ZhiSuoCarBox carbox:listZhiSuoCarBox){
            oneboxjson=new JSONObject();
            Boolean flag=false;
            if(order.getBoxcode().equals(carbox.getName())){
                flag=true;
            }else{
                flag=false;
            }

            if(flag){
                oneboxjson.put("code",carbox.getName());
                oneboxjson.put("isopen","1");
                oneboxjson.put("pos",carbox.getPos());
            }else{
                oneboxjson.put("code",carbox.getName());
                oneboxjson.put("isopen","0");
                oneboxjson.put("pos",carbox.getPos());
            }
            opendoorarray.add(oneboxjson);
        }

        //更改载物箱子状态
        expressManService.updateCarBoxIsEmpty(boxname, carid);



        //生成零售单
        //ZhiSuoUserAddress userAddress=userManService.getZhiSuoUserAddressById(Integer.parseInt(receiptuseraddressid));
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(Integer.parseInt(receiptuserbuildid));
        String receiptcode= RandomStringUtils.random(4, "1234567890");
        expressManService.insertNewSellerOrderByUserId(carid, box.getId(), box.getCode(),receiptuserbuildid,buildinfo.getCode(),userid,receiptusermobile,receiptcode);





        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "派件成功");
        resultObj.put("data", opendoorarray);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 根据用户ID(零售员ID)获取零售列表  0待派件  3已签收   4派送中
     */
    @RequestMapping(value = "/getSellerDeliveryOrderListByUserId")
    public void getSellerDeliveryOrderListByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getSellerDeliveryOrderListByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String status = jsonObject.getString("status");
        Integer page = jsonObject.getInteger("page");
        // 0待派件   3已签收   4派送中
        List<DeliveryOrder> listDeliveryOrder = expressManService.getListSellerDeliveryOrderByUserIdAndStatus(userid, status, page, Constants.PAGESIZE);

        JSONArray jsonArray = new JSONArray();
        JSONObject jo = null;


        for (DeliveryOrder order : listDeliveryOrder) {

            jo = new JSONObject();
            ZhiSuoCar car = expressManService.getCarByCarId(order.getCarid());
            String parkareaid = expressManService.getParkareaidByCarId(car.getId());
            String parkAreaName = expressManService.getParkAreaNameById(parkareaid);

//            ZhiSuoUserAddress userAddress=userManService.getZhiSuoUserAddressById(order.getReceiptuseraddressid());
            ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(order.getReceiptuserbuildid());
            jo.put("carid", car.getId());
            jo.put("carname", car.getName());
            jo.put("parkareaname", parkAreaName+buildinfo.getName());
            jo.put("receiptusermobile", order.getReceiptusermobile());
            jo.put("receipt_time", order.getReceipt_time());
            jo.put("create_time", order.getCreate_time());
            jo.put("orderid", order.getId());
            jo.put("isovertime", order.getIsovertime());
            jsonArray.add(jo);


        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);

    }

    /**
     * 发车
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping(value = "/sendCarByUserid")
    public void sendCarByUserid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("sendCarByUserid-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");

        List<DeliveryOrder> listDeliveryOrder =expressManService.getListNoDeliveryOrderByUserId(userid);




        if(listDeliveryOrder.size()>0 && listDeliveryOrder!=null){

            String carid=listDeliveryOrder.get(0).getCarid()+"";
            String parkareaid=userManService.getParkAreaIdByCarId(listDeliveryOrder.get(0).getCarid());
            ParkArea pa=userManService.getParkAreaById(Integer.parseInt(parkareaid));
            //expressManService.deleteStopBefore(carid);

            ZhiSuoCar car=expressManService.getCarByCarId(Integer.parseInt(carid));

            String putjson="{\n";
            putjson=putjson+ " \"zone_id\": \""+pa.getStrcode()+"\",\n" +
                    " \"depot\": \""+car.getHomestation()+"\",\n" +
                    " \"depot_tw\": [0, 60],\n" + " \"stations\": {\n";
            for(DeliveryOrder order:listDeliveryOrder){
                //将订单置为派送中
                expressManService.updateDeliveryOrderStatusByOrderId(order.getId(),4);
                //根据地址
                //ZhiSuoUserAddress address=userManService.getZhiSuoUserAddressById(order.getReceiptuseraddressid());
                ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(order.getReceiptuserbuildid());
                putjson=putjson+ " \"" +buildinfo.getCode()+
                        "\": [0, 60],";
            }
            putjson=putjson.substring(0,putjson.length()-1) +" },\n" +
                    " \"speed\": 10,\n" +
                    " \"wait\": 2 }";

            //System.out.println("----------syncDataTask--------putjson--------"+putjson);

            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post=new HttpPost("http://49.235.73.243:80/tsptwrd");

            StringEntity stringEntity = new StringEntity(putjson);
            stringEntity.setContentType("application/json");
            post.setEntity(stringEntity);
            // 执行get请求，得到返回体
            HttpResponse response = client.execute(post);


            //System.out.println("data----"+response.getStatusLine().toString());
            // 判断是否正常返回
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 解析数据
                String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                //System.out.println("data----"+data);
                if(StringUtils.isNotEmpty(data)){
                    JSONObject datajson=JSONObject.parseObject(data);
                    JSONArray jsonArray=datajson.getJSONArray("sequence");
                    if(jsonArray.size()>0){
                        //将以前的发车数据置为1
                        userManService.updateZhiSuoCarNextStopListStauts(carid);
                        String nextstop="";
                        for(int i=1;i<jsonArray.size();i++){
                            //存储
                            if(i==1){
                                nextstop=jsonArray.get(i).toString();
                            }

                            //System.out.println("nextstop------"+jsonArray.get(i));
                            userManService.insertNewZhiSuoCarNextStopList(carid,jsonArray.get(i).toString());

                        }
                        //发送第一个车指令入库
                        ZhiSuoCar zhiSuoCar=userManService.getZhiSuoCarByCarId(carid);

                        userManService.insertNewZhiSuoCarSendNextStopTcp(zhiSuoCar.getSn(),zhiSuoCar.getId(),zhiSuoCar.getName(),nextstop,zhiSuoCar.getHomestation());

                        //根据下一站指令，获取下一个用户
                        List<DeliveryOrder> listNextStopDeliveryOrder=expressManService.getListNextDeliveryOrderByNextStop(nextstop,zhiSuoCar.getId()+"");



                        if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                            for(DeliveryOrder nextorder:listNextStopDeliveryOrder){
                                String[] params = new String[]{nextorder.getReceiptcode()};
                                String[] phoneNumbers =new String[]{nextorder.getReceiptusermobile()};
                                //发送短信
                                //SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                                userManService.insertNewZhiSuoCarSendNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",1);
                                //语音短信
                                userManService.insertNewZhiSuoCarNextStopSms("5,"+nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",5);

                            }
                        }


                    }


                }

            }

        }else{
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "无订单，不发车");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "发车成功");
        responseData(resultObj.toString(), resp);


    }


    /**
     *根据订单ＩＤ开箱
     */
    @RequestMapping(value = "/openCarDoorByOrderId")
    public void openCarDoorByOrderId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("openCarDoorByOrderId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");

        DeliveryOrder order = userManService.getDeliveryOrderById(orderid);


        ZhiSuoCar car = expressManService.getCarByCarId(order.getCarid());
        List<ZhiSuoCarBox> listZhiSuoCarBox = expressManService.getListZhiSuoCarBoxByCarId(order.getCarid()+"");
        //获取TCP服务器地址
        String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");
        //下发开箱指令
        String tcpresult = TcpUtil.openDoor(car, order, listZhiSuoCarBox,tcp_url);
        if(StringUtils.isNotEmpty(tcpresult)){
            JSONObject tcpresultjson=JSONObject.parseObject(tcpresult);
            String tcpresultjsonerrorCode=tcpresultjson.getString("errorCode");
            if(tcpresultjsonerrorCode.equals("1")){
                responseErrorData("开门失败，请再试一次", resp);
                return;
            }
        }

        expressManService.updateDelOrderStatusByOrderId(orderid);

        //将箱子与订单关联关闭

        expressManService.updateDelCarBoxIsEmpty(order.getBoxcode(),car.getId()+"");


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "开箱成功");
        responseData(resultObj.toString(), resp);
    }



    /**
     *根据订单ＩＤ删除订单
     */
    @RequestMapping(value = "/deleteOrderByOrderId")
    public void deleteOrderByOrderId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("deleteOrderByOrderId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");

        expressManService.updateDelOrderStatusByOrderId(orderid);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "删除成功");
        responseData(resultObj.toString(), resp);
    }



    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
